package nanzhuli.user.svc.util;

import lombok.extern.slf4j.Slf4j;
import nanzhuli.user.svc.model.resp.excel.OriginalRecord;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * excel操作工具类
 * @Date: 2018/7/2 15:04
 */
@Slf4j
public class ImportExcelUtil {

    private static final String EXCEL2003L = ".xls"; // 2003- 版本的excel
    private static final String EXCEL2007U = ".xlsx"; // 2007+ 版本的excel

    private static final Integer TITLEROW = 3; // 取第N行为标题
    private static final String SHEETNAME = "原始记录"; // 原始记录的sheet名

    /**
     * 将流中的Excel数据转成List<Map>
     *
     * @param in       输入流
     * @param fileName 文件名（判断Excel版本）
     * @param mapping  字段名称映射
     * @return List<Map<String, Object>> excel数据
     */
    private static List<Map<String, Object>> parseExcel(InputStream in, String fileName,
                                                        Map<String, String> mapping,
                                                        Integer titleRow, String sheetName) throws Exception {
        // 默认取第1行为标题行
        titleRow = StringUtils.isEmpty(titleRow) ? 1 : titleRow;

        // 根据文件名来创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        // 返回数据
        List<Map<String, Object>> ls = new ArrayList<>();

        // 遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if(!StringUtils.isEmpty(sheetName) && !sheetName.equals(sheet.getSheetName())){
                continue;
            }
            // 取第三行为标题
            row = sheet.getRow(titleRow - 1);
            String title[] = null;
            if (row != null) {
                title = new String[row.getLastCellNum()];
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    title[y] = (String) getCellValue(cell);
                }
            } else {
                continue;
            }

            // 遍历当前sheet中的所有行
            for (int j = titleRow; j < sheet.getLastRowNum() + 1; j++) {
                row = sheet.getRow(j);
                Map<String, Object> m = new HashMap<>();
                // 遍历所有的列
                for (int y = 0; y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    String key = title[y];
                    if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(cell)) {
                        m.put(mapping.get(key), getCellValue2(cell));
                    }
                }
                ls.add(m);
            }
        }
        return ls;
    }

    private static boolean isMergedRegion(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress range = sheet.getMergedRegion(i);
            int firstColumn = range.getFirstColumn();
            int lastColumn = range.getLastColumn();
            int firstRow = range.getFirstRow();
            int lastRow = range.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    return true;
                }
            }
        }
        return false;
    }

    public static String getMergedRegionValue(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();

        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress ca = sheet.getMergedRegion(i);
            int firstColumn = ca.getFirstColumn();
            int lastColumn = ca.getLastColumn();
            int firstRow = ca.getFirstRow();
            int lastRow = ca.getLastRow();

            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColumn && column <= lastColumn) {
                    Row fRow = sheet.getRow(firstRow);
                    Cell fCell = fRow.getCell(firstColumn);
                    return getMyCellValue(fCell);
                }
            }
        }
        return null;
    }

    private static String getMyCellValue(Cell cell) {
        if (cell == null) return "";
        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return cell.getCellFormula();
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        }
        return "";
    }

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     * @param inStr ,fileName
     * @return Workbook Workbook对象
     */
    private static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf('.'));
        if (EXCEL2003L.equals(fileType)) {
            wb = new HSSFWorkbook(inStr); // 2003-
        } else if (EXCEL2007U.equals(fileType)) {
            wb = new XSSFWorkbook(inStr); // 2007+
        } else {
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }

    /**
     * 描述：对表格中数值进行格式化
     * @param cell 表格
     * @return Object 获取表格格式后的数据
     */
    private static Object getCellValue(Cell cell) {
        Object value = null;
        DecimalFormat df = new DecimalFormat("#.##"); // 格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
        DecimalFormat df2 = new DecimalFormat(); // 格式化数字
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    value = cell.getStringCellValue();
                } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                    value = sdf.format(cell.getDateCellValue());
                } else {
                    value = df2.format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            default:
                break;
        }
        return value;
    }

    /**
     * 描述：对表格中数值进行格式化（该方法有对公式类型的值进行处理，注意得到的浮点数不精确）
     * @param cell 表格
     * @return Object 获取表格格式后的数据
     */
    private static Object getCellValue2(Cell cell) {
        Object value = null;
        DecimalFormat df = new DecimalFormat("#.##"); // 格式化number String字符
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
        DecimalFormat df2 = new DecimalFormat(); // 格式化数字
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    value = cell.getStringCellValue();
                } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                    value = sdf.format(cell.getDateCellValue());
                } else {
                    value = df2.format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            case Cell.CELL_TYPE_FORMULA:// 公式
                value = String.valueOf(cell.getNumericCellValue());
            default:
                break;
        }
        return value;
    }

    public static List<OriginalRecord> importExcel(MultipartFile partFile) throws Exception {
        String fileName = partFile.getOriginalFilename();
        InputStream inputStream = partFile.getInputStream();
        Map<String, String> m = new HashMap<>();
        m.put("姓名", "name");
        m.put("考勤组", "attendanceGroup");
        m.put("部门", "department");
        m.put("工号", "jobNum");
        m.put("职位", "position");
        m.put("考勤日期", "attendanceDate");
        m.put("考勤时间", "attendanceTime");
        m.put("打卡时间", "checkInTime");
        m.put("打卡结果", "checkInResult");
        m.put("打卡地址", "checkInAddr");
        m.put("打卡备注", "checkInRemark");
        m.put("异常打卡原因", "abnormalCheckIn");
        List<Map<String, Object>> ls = parseExcel(inputStream, fileName, m, TITLEROW, SHEETNAME);
        List<OriginalRecord> list = new ArrayList<>();
        for (Map<String, Object> l : ls) {
            list.add(BeanToMapUtils.toBean(OriginalRecord.class, l));
        }
        return list;
    }
}
